<template>
  <div class="rev-editor">
    <Editor v-model="html" ref="editorRef" :editorConfig="editorConfig" @change="onChange" />
  </div>
</template>

<script>
import { Editor } from '@/components/CKEditor'
import axios from 'axios'
import { useCache } from '@/hooks/web/useCache'
import { debounce } from 'lodash-es'
import { getImageBase64 } from '@/utils/file'
const { wsCache } = useCache()

export default {
  name: 'RevEditor',
  components: { Editor },
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      editor: null,
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      editorConfig: {
        placeholder: '请输入内容...',
        // autoFocus: false,

        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {}
      }
    }
  },
  computed: {
    html: {
      get: function () {
        return this.modelValue
      },
      set: function (value) {
        this.$emit('update:modelValue', value)
      }
    }
  },
  watch: {
    html() {
      this.debounceUpdateImage()
    }
  },
  async created() {
    //获取数据
    //禁用修改
    const editor = this.editor
    if (editor == null) return
    editor.disable()
  },
  beforeUnmount() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁 editor ，重要！！！
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
    },
    async onChange(editor) {
      //   console.log('onChange', editor.getHtml()) // onChange 时获取编辑器最新内容
      this.html = editor.getHtml()
      this.$emit('change', this.html)
    },
    async submit() {
      //   console.log(typeof this.html, this.html)
      const { data } = await axios.get('/api/save', {
        params: { html: this.html }
      })
      console.log(this.html)
      if (data.states === 'ok') {
        alert('保存成功')
        this.html = data.data
        const editor = this.editor
        if (editor == null) return
        //禁用修改
        editor.disable()
      }
    },
    disableHandler() {
      const editor = this.editor
      if (editor == null) return
      //启用修改
      // editor.enable();
      editor.disable()
    },
    debounceUpdateImage: debounce(async function () {
      this.$nextTick(() => {
        // eslint-disable-next-line @typescript-eslint/no-this-alias
        const me = this
        this.$el.querySelectorAll('img').forEach((img) => {
          // 如果图片地址不是base64图片
          if (!/^data:\S+;base64,/.test(img.src)) {
            if (img.complete) {
              if (img.src) {
                this.html = this.html.replace(img.src, getImageBase64(img))
              }
            } else {
              img.onload = function () {
                if (img.src) {
                  me.html = me.html.replace(img.src, getImageBase64(img))
                }
              }
            }
          }
          let p = img.parentNode
          if (p.classList.contains('image-inline')) {
            p = p.parentNode
          }
          if (p?.style?.height === '0px') {
            p.style.height = 'auto'
          }
          if (p?.style?.width === '0px') {
            p.style.width = 'auto'
          }
        })
      })
    }, 500)
  }
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped lang="less">
.rev-editor {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index: 10;

  &.w-e-full-screen-container {
    z-index: 3000;
  }

  .main-editor {
    flex: 1;
    overflow-y: hidden;
  }

  :deep(.ck) {
    &.ck-editor__editable {
      span.image-inline {
        left: unset !important;
        top: unset !important;
      }
    }

    .ck-toolbar {
      background-color: var(--el-bg-color);
      color: var(--el-text-color-primary);
    }

    .ck-button {
      &:hover {
        background-color: var(--el-hover-bg-color);
      }
    }
  }
}
</style>
